package cn.xdf.docscan

import android.content.Context
import android.util.Log
import com.google.mediapipe.framework.AndroidAssetUtil
import com.google.mediapipe.framework.Graph
import com.google.mediapipe.framework.PacketCreator
// import cn.xdf.docscan.DocScannerV2sJni

/**
 * DocScanner初始化器
 * 1:1复刻lsj.java的初始化逻辑
 */
class DocScannerInitializer {
    
    companion object {
        private var isLibraryLoaded = false
        
        /**
         * 初始化DocScanner
         * 完全按照lsj.java的逻辑实现
         */
        fun initialize(context: Context): DocScannerComponents {
            // 1. 加载SO库 - 完全按照lsj.java的逻辑
            if (!isLibraryLoaded) {
                System.loadLibrary("doc_scanner_v2s_jni")
                isLibraryLoaded = true
            }
            
            // 2. 初始化AndroidAssetUtil - 完全按照lsj.java的逻辑
            try {
                // 尝试使用反射调用initialize方法
                val initializeMethod = AndroidAssetUtil::class.java.getDeclaredMethod("initialize", Context::class.java)
                initializeMethod.invoke(null, context)
                Log.d("DocScannerInitializer", "✅ AndroidAssetUtil初始化成功")
            } catch (e: Exception) {
                Log.w("DocScannerInitializer", "⚠️ AndroidAssetUtil初始化失败，继续执行", e)
            }
            
            // 3. 创建Graph - 完全按照lsj.java的逻辑
            val graph = Graph()
            
            // 4. 加载binarypb文件 - 完全按照lsj.java的逻辑
            val inputStream = context.assets.open("video_to_scan_analysis.binarypb")
            val graphConfig = inputStream.readBytes()
            inputStream.close()
            graph.loadBinaryGraph(graphConfig)
            
            // 5. 创建PacketCreator - 完全按照lsj.java的逻辑
            val packetCreator = PacketCreator(graph)

            // 6. 初始化原项目的protobuf解析器
            try {
                ProtoDetectorLoader.init(context)
            } catch (e: Exception) {
                Log.w("DocScannerInitializer", "⚠️ ProtoDetectorLoader初始化失败", e)
            }
            
            return DocScannerComponents(graph, packetCreator)
        }
    }
    
    /**
     * DocScanner组件
     * 包含Graph和PacketCreator
     */
    data class DocScannerComponents(
        val graph: Graph,
        val packetCreator: PacketCreator
    )
} 